package com.cctv.haierstore.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.cctv.common.to.es.SkuEsModel;
import com.cctv.common.utils.R;
import com.cctv.haierstore.search.config.HaierStoreElasticConfig;
import com.cctv.haierstore.search.constant.EsConstant;
import com.cctv.haierstore.search.feign.ProductFeignService;
import com.cctv.haierstore.search.service.EsearchService;
import com.cctv.haierstore.search.vo.AttrResponseVo;
import com.cctv.haierstore.search.vo.SearchParamVo;
import com.cctv.haierstore.search.vo.SearchResultVo;
import org.apache.commons.lang3.StringUtils;
import org.apache.lucene.search.join.ScoreMode;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.bucket.nested.NestedAggregationBuilder;
import org.elasticsearch.search.aggregations.bucket.nested.ParsedNested;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedLongTerms;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedStringTerms;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.naming.directory.SearchResult;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author huayi
 * @date 2023年12月24日 9:34
 */
@Service
public class EsearchServiceImpl implements EsearchService{
    @Resource
    RestHighLevelClient restHighLevelClient;

    @Autowired
    ProductFeignService productFeignService;
    /**
     * 返回检索的结果
     */
    @Override
    public SearchResultVo search(SearchParamVo searchParamVo) {
        //1.构建请求
        SearchRequest searchRequest = buildSearchRequest(searchParamVo);
        System.out.println("构建的请求"+searchRequest.source().toString());
        //2.执行请求
        SearchResponse response=null;
        try {
            response = restHighLevelClient.search(searchRequest, HaierStoreElasticConfig.COMMON_OPTIONS);
        } catch (IOException e) {
            e.printStackTrace();
        }
        //3.封装返回结果
        SearchResultVo searchResultVo = buildSearchResultVo(response, searchParamVo);
        return searchResultVo;
    }
    //构建请求
    private SearchRequest buildSearchRequest(SearchParamVo searchParamVo) {
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        /**
         * 查询
         */
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        //1.检索关键字
        if(!StringUtils.isEmpty(searchParamVo.getKeyword())){
            boolQuery.must(QueryBuilders.matchQuery("skuTitle",searchParamVo.getKeyword()));
        }
        //2.过滤三级分类
        if(searchParamVo.getCatalog3Id()!=null){
            boolQuery.filter(QueryBuilders.termQuery("catalogId",searchParamVo.getCatalog3Id()));
        }
        //3.过滤是否有库存
        if(searchParamVo.getHasStock()!=null){
            boolQuery.filter(QueryBuilders.termQuery("hasStock",searchParamVo.getHasStock()==1));
        }
        //4.过滤价格区间：_500/1_500/500_
        if(!StringUtils.isEmpty(searchParamVo.getSkuPrice())){
            String skuPrice = searchParamVo.getSkuPrice();
            String[] s = searchParamVo.getSkuPrice().split("_");
            if(s.length==1){
                if(skuPrice.startsWith("_")){
                    boolQuery.filter(QueryBuilders.rangeQuery("skuPrice").lte(s[0]));
                }
                if(skuPrice.endsWith("_")){
                    boolQuery.filter(QueryBuilders.rangeQuery("skuPrice").gte(s[0]));
                }
            }else {
                boolQuery.filter(QueryBuilders.rangeQuery("skuPrice").gte(s[0]).lte(s[1]));
            }
        }
        //5.过滤品牌
        if(searchParamVo.getBrandId()!=null){
            boolQuery.filter(QueryBuilders.termsQuery("brandId",searchParamVo.getBrandId()));
        }
        //6.过滤\属性
        if(searchParamVo.getAttrs()!=null && searchParamVo.getAttrs().size()>0){
            for (String attr : searchParamVo.getAttrs()) {
                String[] attrInfo = attr.split("_");
                BoolQueryBuilder attrBoolQuery = QueryBuilders.boolQuery();
                //6.1、属性id
                attrBoolQuery.must(QueryBuilders.termQuery("attrs.attrId",attrInfo[0]));
                //6.2、属性值
                attrBoolQuery.must(QueryBuilders.termsQuery("attrs.attrValue",attrInfo[1].split(":")));
                boolQuery.filter(QueryBuilders.nestedQuery("attrs",attrBoolQuery, ScoreMode.None));
            }
        }
        searchSourceBuilder.query(boolQuery);
        /**
         * 排序
         * sort=saleCount_asc/desc
         * sort=skuPrice_asc/desc
         * sort=hotScore_asc/desc
         * 分页
         */
        //7.排序
        if(!StringUtils.isEmpty(searchParamVo.getSort())){
            String[] sortInfo = searchParamVo.getSort().split("_");
            if(sortInfo[0].equalsIgnoreCase("skuPrice")){
                if(sortInfo[1].equalsIgnoreCase(SortOrder.ASC.toString())){
                    searchSourceBuilder.sort("skuPrice", SortOrder.ASC);
                }
                if(sortInfo[1].equalsIgnoreCase(SortOrder.DESC.toString())){
                    searchSourceBuilder.sort("skuPrice", SortOrder.DESC);
                }
            }
        }
        //8.页码
        if(searchParamVo.getPageNum()!=null){
            searchSourceBuilder.from((searchParamVo.getPageNum()-1)*EsConstant.SEARCH_PAGESIZE);
            searchSourceBuilder.size(EsConstant.SEARCH_PAGESIZE);
        }
        /**
         * 高亮、聚合
         */
        //9.高亮
        if (!StringUtils.isEmpty(searchParamVo.getKeyword())){
            HighlightBuilder highlightBuilder = new HighlightBuilder();
            highlightBuilder.field("skuTitle").preTags("<b style=color:red>").postTags("</b>");
            searchSourceBuilder.highlighter(highlightBuilder);
        }
        //10.聚合
        //10.1、品牌
        TermsAggregationBuilder brandIdAgg = AggregationBuilders.terms("brand_agg").field("brandId").size(50);//品牌id
        brandIdAgg.subAggregation(AggregationBuilders.terms("brand_name_agg").field("brandName").size(1));//品牌名
        brandIdAgg.subAggregation(AggregationBuilders.terms("brand_img_agg").field("brandImg").size(1));//品牌图片
        searchSourceBuilder.aggregation(brandIdAgg);
        //10.2、分类
        TermsAggregationBuilder catalogIdAgg = AggregationBuilders.terms("catalog_agg").field("catalogId").size(50);//分类id
        catalogIdAgg.subAggregation(AggregationBuilders.terms("catalog_name_agg").field("catalogName").size(1));//分类名
        searchSourceBuilder.aggregation(catalogIdAgg);
        //10.3、属性
        NestedAggregationBuilder attrsNestedAgg = AggregationBuilders.nested("attr_agg", "attrs");
        TermsAggregationBuilder attrAgg = AggregationBuilders.terms("attr_id_agg").field("attrs.attrId").size(50);
        attrAgg.subAggregation(AggregationBuilders.terms("attr_name_agg").field("attrs.attrName").size(1));
        attrAgg.subAggregation(AggregationBuilders.terms("attr_value_agg").field("attrs.attrValue").size(50));
        attrsNestedAgg.subAggregation(attrAgg);
        searchSourceBuilder.aggregation(attrsNestedAgg);

        SearchRequest searchRequest = new SearchRequest(new String[]{EsConstant.PRODUCT},searchSourceBuilder);
        return searchRequest;
    }

    /**
     * 构建结果数据
     * @param response  执行检索请求获得的响应数据
     * @return  封装成需要的指定格式并返回
     */
    private SearchResultVo buildSearchResultVo(SearchResponse response, SearchParamVo param) {

        SearchResultVo result = new SearchResultVo();

        // 1、返回的所有查询到的商品
        SearchHits hits = response.getHits();
        List<SkuEsModel> esModels = new ArrayList<>();
        if (hits.getHits()!=null && hits.getHits().length>0) {
            for (SearchHit hit : hits.getHits()) {
                String sourceAsString = hit.getSourceAsString();
                SkuEsModel esModel = JSON.parseObject(sourceAsString, SkuEsModel.class);
                if (!StringUtils.isEmpty(param.getKeyword())) {
                    HighlightField skuTitle = hit.getHighlightFields().get("skuTitle");
                    String string = skuTitle.getFragments()[0].string();
                    esModel.setSkuTitle(string);
                }
                esModels.add(esModel);
            }
        }
        result.setProducts(esModels);


        // 2、当前所有商品涉及到的所有属性信息
        List<SearchResultVo.AttrVo> attrVos = new ArrayList<>();
        ParsedNested attrs_agg = response.getAggregations().get("attr_agg");
        ParsedLongTerms attr_id_agg = attrs_agg.getAggregations().get("attr_id_agg");
        for (Terms.Bucket bucket : attr_id_agg.getBuckets()) {
            SearchResultVo.AttrVo attrVo = new SearchResultVo.AttrVo();
            // 1、得到属性的id
            long attrId = bucket.getKeyAsNumber().longValue();
            // 2、得到属性的名字
            String attrName = ((ParsedStringTerms) bucket.getAggregations().get("attr_name_agg")).getBuckets().get(0).getKeyAsString();
            // 3、得到属性的所有值
            List<String> attrValues = ((ParsedStringTerms) bucket.getAggregations().get("attr_value_agg")).getBuckets().stream().map(item -> {
                String keyAsString = ((Terms.Bucket) item).getKeyAsString();
                return keyAsString;
            }).collect(Collectors.toList());
            attrVo.setAttrId(attrId);
            attrVo.setAttrName(attrName);
            attrVo.setAttrValue(attrValues);
            attrVos.add(attrVo);
        }
        result.setAttrs(attrVos);

        // 3、保存当前商品所涉及的所有品牌信息
        List<SearchResultVo.BrandVo> brandVos = new ArrayList<>();
        ParsedLongTerms brand_agg = response.getAggregations().get("brand_agg");
        for (Terms.Bucket bucket : brand_agg.getBuckets()) {
            SearchResultVo.BrandVo brandVo = new SearchResultVo.BrandVo();
            // 1、得到品牌的id
            long brandId = bucket.getKeyAsNumber().longValue();
            // 2、得到品牌的name
            String brandName = ((ParsedStringTerms) bucket.getAggregations().get("brand_name_agg")).getBuckets().get(0).getKeyAsString();
            // 3、得到品牌的img
            String brandImg = ((ParsedStringTerms) bucket.getAggregations().get("brand_img_agg")).getBuckets().get(0).getKeyAsString();
            brandVo.setBrandId(brandId);
            brandVo.setBrandName(brandName);
            brandVo.setBrandImg(brandImg);
            brandVos.add(brandVo);
        }
        result.setBrands(brandVos);

        // 4、保存当前商品所涉及的所有分类信息
        List<SearchResultVo.CatalogVo> catalogVos = new ArrayList<>();
        ParsedLongTerms catalog_agg = response.getAggregations().get("catalog_agg");
        List<? extends Terms.Bucket> buckets = catalog_agg.getBuckets();
        for (Terms.Bucket bucket : buckets) {
            SearchResultVo.CatalogVo catalogVo = new SearchResultVo.CatalogVo();
            // 得到分类id
            catalogVo.setCatalogId(bucket.getKeyAsNumber().longValue());
            // 得到分类name
            ParsedStringTerms catalog_name_agg = bucket.getAggregations().get("catalog_name_agg");
            String catalog_name = catalog_name_agg.getBuckets().get(0).getKeyAsString();
            catalogVo.setCatalogName(catalog_name);
            catalogVos.add(catalogVo);
        }
        result.setCatalogs(catalogVos);

        // 5、分页信息
        // 分页信息-页码
        result.setPageNum(param.getPageNum());
        // 分页信息-总记录数
        long total = hits.getTotalHits().value;
        result.setTotal(total);
        // 分页信息-总页码 (总记录数 对 每页数求余数）
        int totalPages = (int)total%EsConstant.SEARCH_PAGESIZE==0 ? ((int)total/EsConstant.SEARCH_PAGESIZE) : ((int)total/EsConstant.SEARCH_PAGESIZE+1);
        result.setTotalPages(totalPages);
        // 分页信息-导航栏
        List<Integer> pageNavs = new ArrayList<>();
        for (int i = 1; i <= totalPages; i++) {
            pageNavs.add(i);
        }
        result.setPageNavs(pageNavs);
        //6、构建面包屑导航
        if (param.getAttrs() != null && param.getAttrs().size() > 0) {
            List<SearchResultVo.NavVo> collect = param.getAttrs().stream().map(attr -> {
                //1、分析每一个attrs传过来的参数值
                SearchResultVo.NavVo navVo = new SearchResultVo.NavVo();
                String[] s = attr.split("_");
                navVo.setNavValue(s[1]);
                R r = productFeignService.attrInfo(Long.parseLong(s[0]));
                if (r.getCode() == 0) {
                    AttrResponseVo data = r.getData("attr", new TypeReference<AttrResponseVo>(){});
                    navVo.setNavName(data.getAttrName());
                } else {
                    navVo.setNavName(s[0]);
                }

                //2、取消了这个面包屑以后，我们要跳转到哪个地方，将请求的地址url里面的当前置空
                //拿到所有的查询条件，去掉当前
                String encode = null;
                try {
                    encode = URLEncoder.encode(attr,"UTF-8");
                    encode.replace("+","%20");  //浏览器对空格的编码和Java不一样，差异化处理
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
                String replace = param.get_queryString().replace("&attrs=" + attr, "");
                navVo.setLink("http://search.haierstore.com/list.html?" + replace);

                return navVo;
            }).collect(Collectors.toList());

            result.setNavs(collect);
        }

        return result;
    }

    public static void main(String[] args) {
        String str1 = "aaa";
        String str2 = "aaa";
        System.out.println(str1.hashCode());
        System.out.println(str2.hashCode());

    }

}
